package cn.springcloud.fix.common.core.handler;

import cn.hutool.core.util.ArrayUtil;
import cn.springcloud.fix.common.core.base.BaseResponse;
import cn.springcloud.fix.common.core.enums.ResponseEnum;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.server.ResponseStatusException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.*;

/**
 * 全局的的异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponse handleValidationException(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<?> cv : e.getConstraintViolations()) {
            String fieldName = ((PathImpl) cv.getPropertyPath()).getLeafNode().asString();
            String message = cv.getMessage();
            sb.append(fieldName).append(" ").append(message);
        }
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(-1, sb.toString());
        return response;
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse handleIllegalArgumentException(IllegalArgumentException e) {
        log.error(ResponseEnum.ILLEGAL_ARGUMENT.getMessage() + ":" + e.getMessage());
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.ILLEGAL_ARGUMENT);
        return response;
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("missing servlet request parameter exception:{}", e.getMessage());
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.MISSING_ARGUMENT);
        return response;
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse handleMethodArgumentTypeMismatchExceptionException(MethodArgumentTypeMismatchException e) {
        log.error(ResponseEnum.ILLEGAL_ARGUMENT_TYPE.getMessage() + ":" + e.getMessage());
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.ILLEGAL_ARGUMENT_TYPE);
        return response;
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public BaseResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error(ResponseEnum.METHOD_NOT_ALLOWED.getMessage() + ":" + e.getMessage());
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.METHOD_NOT_ALLOWED);
        return response;
    }

    @ExceptionHandler(IllegalStateException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse handleIllegalStateException(IllegalStateException e) {
        log.error(e.getMessage(), e);
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.ILLEGAL_STATE);
        return response;
    }

    @ExceptionHandler(value = {RuntimeException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse handle(RuntimeException ex) {
        log.error("runtime exception:{}", ex.getMessage());
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.INTERNAL_SERVER_ERROR);
        return response;
    }

    @ExceptionHandler(value = {ResponseStatusException.class})
    public BaseResponse handle(ResponseStatusException ex) {
        log.error("response status exception:{}", ex.getMessage());
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.INTERNAL_SERVER_ERROR);
        return response;
    }

    @ExceptionHandler(value = {MultipartException.class})
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse uploadFileLimitException(MultipartException ex) {
        log.error("upload file size limit:{}", ex.getMessage());
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.MULTIPART_TOO_LARGE);
        return response;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResponse handleException(Exception e) {
        log.error(e.getMessage(), e);
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(ResponseEnum.INTERNAL_SERVER_ERROR);
        return response;
    }

    /**
     * AccessDeniedException
     */
    // @ExceptionHandler(AccessDeniedException.class)
    // @ResponseStatus(HttpStatus.FORBIDDEN)
    // public R handleAccessDeniedException(AccessDeniedException e) {
    //     MessageSourceAccessor accessor = SpringSecurityMessageSource.getAccessor();
    //     String msg = accessor.getMessage("AbstractAccessDecisionManager.accessDenied", e.getMessage());
    //     log.error("拒绝授权异常信息 ex={}", msg, e);
    //     return R.builder().msg(msg).code(-1).build();
    // }
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResponse bodyValidExceptionHandler(MethodArgumentNotValidException e) {
        BaseResponse response = new BaseResponse();

        List<FieldError> fieldErrors = Optional.ofNullable(e).map(MethodArgumentNotValidException::getBindingResult).map(BindingResult::getFieldErrors).orElse(new ArrayList<>());
        log.error("参数绑定异常,ex = {}", JSON.toJSONString(fieldErrors));
        if (ArrayUtil.isEmpty(fieldErrors)) {
            response.setCodeAndMessage(-1, "未知异常!");
            return response;
        }

        StringBuilder sb = new StringBuilder();
        for (FieldError error : fieldErrors) {
            sb.append(error.getField()).append(" ").append(error.getDefaultMessage());
        }
        response.setCodeAndMessage(-1, sb.toString());
        return response;
    }

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        StringBuilder sb = new StringBuilder();
        for (FieldError error : e.getFieldErrors()) {
            sb.append(error.getField()).append(" ").append(error.getDefaultMessage());
        }
        BaseResponse response = new BaseResponse();
        response.setCodeAndMessage(-1, sb.toString());
        return response;
    }
}
